﻿using AutoMapper;
using QuartzServices.Application.SystemLog.Models;
using QuartzServices.Domain.Core.Models;
using QuartzServices.Domain.DomainModels;
using QuartzServices.Domain.Interfaces;
using System.Linq.Expressions;

namespace QuartzServices.Application.SystemLog
{
    public interface ISystemLogApplication
    {
        Task<SystemLogPageResult> PageList(SystemLogPageRequestModel requestModel);

        Task Delete(List<string> ids);
    }

    public class SystemLogApplication : ISystemLogApplication
    {

        private readonly IRepository<SerilogModel> _repository;
        private readonly IMapper _mapper;
        public SystemLogApplication(IRepository<SerilogModel> repository,IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        public async Task Delete(List<string> ids)
        {
            await _repository.RemoveRange(ids);
        }

        public async Task<SystemLogPageResult> PageList(SystemLogPageRequestModel requestModel)
        {
            Expression<Func<SerilogModel, bool>> expression = d => d.Level == requestModel.LogLevel &&
            (string.IsNullOrEmpty(requestModel.Message) || d.Message.Contains(requestModel.Message)) &&
            (string.IsNullOrEmpty(requestModel.SourceContext) || d.SourceContext.Contains(requestModel.SourceContext)) &&
            (string.IsNullOrEmpty(requestModel.FilePath) || d.FilePath.Contains(requestModel.FilePath)) &&
            (string.IsNullOrEmpty(requestModel.MemberName) || d.MemberName.Contains(requestModel.MemberName));

            var count = await _repository.CountAsync(expression);
            var list = await _repository.PageListAsync(expression, requestModel.offset, requestModel.limit);

            return new SystemLogPageResult
            {
                total = count,
                rows = _mapper.Map<List<SystemLogPageModel>>(list)
            };
        }
    }
}
